#!/usr/bin/env bash
#
# Summary: Set or show the shell-specific Java version
#
# Usage: jenv shell <version>
#        jenv shell --unset
#
# Sets a shell-specific Java version by setting the `JENV_VERSION'
# environment variable in your shell. This version overrides local
# application-specific versions and the global version.
#
# <version> should be a string matching a Java version known to jenv.
# The special version string `system' will use your default system Java.
# Run `jenv versions' for a list of available Java versions.

set -e
[ -n "$JENV_DEBUG" ] && set -x

# Provide jenv completions
if [ "$1" = "--complete" ]; then
  echo --unset
  echo system
  exec jenv-versions --bare
fi

version="$1"

if [ -z "$version" ]; then
  if [ -z "$JENV_VERSION" ]; then
    echo "jenv: no shell-specific version configured" >&2
    exit 1
  else
    echo "echo \"\$JENV_VERSION\""
    exit
  fi
fi

if [ "$version" = "--unset" ]; then
  case "$JENV_SHELL" in
    bash|zsh)
      echo "unset JENV_VERSION"
      ;;
    fish)
      echo "set -e JENV_VERSION || true"
      ;;
  esac
  exit
fi

# Make sure the specified version is installed.
if jenv-prefix "$version" >/dev/null; then
  echo "export JENV_VERSION=\"${version}\""
else
  echo "return 1"
  exit 1
fi
